package com.gs.djys.checkfragments.sign;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.gs.djys.Base.AddBean;
import com.gs.djys.Base.DictationResult;
import com.gs.djys.Base.MyAppliCation;
import com.gs.djys.Base.Urls;
import com.gs.djys.R;
import com.gs.djys.Util.NoRecycleView;
import com.gs.djys.Util.ToastUtils;
import com.gs.djys.Util.Utils;
import com.gs.djys.adapter.LGRecycleViewAdapter;
import com.gs.djys.adapter.LGViewHolder;
import com.gs.djys.bigpic.BigPicActivity;
import com.gs.djys.checkfragments.inquest.AddInquestBean;
import com.gs.djys.mvp.MVPBaseFragment;
import com.gs.djys.signs.SignsBean;
import com.gs.djys.signtext.SignTextActivity;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class SignFragment extends MVPBaseFragment<SignContract.View, SignPresenter> implements SignContract.View, RadioGroup.OnCheckedChangeListener {


    @Bind(R.id.rb_Male)
    RadioButton rbMale;
    @Bind(R.id.rb_FeMale)
    RadioButton rbFeMale;
    @Bind(R.id.rg_sex)
    RadioGroup rgSex;
    @Bind(R.id.sljg_lay)
    LinearLayout sljgLay;
    @Bind(R.id.jcsj_et)
    TextView jcsjEt;
    @Bind(R.id.jcsj_lay)
    LinearLayout jcsjLay;
    @Bind(R.id.jcdd_et)
    TextView jcddEt;
    @Bind(R.id.cphm_te)
    TextView cphmTe;
    @Bind(R.id.zhfb_te)
    TextView zhfbTe;
    @Bind(R.id.hwmc_te)
    TextView hwmcTe;
    @Bind(R.id.hwcc_c)
    TextView hwccC;
    @Bind(R.id.hwcc_k)
    TextView hwccK;
    @Bind(R.id.hwcc_g)
    TextView hwccG;
    @Bind(R.id.chzz_c)
    TextView chzzC;
    @Bind(R.id.chzz_k)
    TextView chzzK;
    @Bind(R.id.chzz_g)
    TextView chzzG;
    @Bind(R.id.chzz_et)
    TextView chzzEt;
    @Bind(R.id.yslx_te)
    TextView yslxTe;
    @Bind(R.id.fj_te)
    TextView fjTe;
    @Bind(R.id.bz_et)
    EditText bzEt;
    @Bind(R.id.INQuality)
    RelativeLayout INQuality;
    @Bind(R.id.bz_lay)
    RelativeLayout bzLay;
    @Bind(R.id.gd_te)
    TextView gdTe;
    @Bind(R.id.chzqz_img)
    ImageView chzqzImg;
    @Bind(R.id.chz_lay)
    LinearLayout chzLay;
    @Bind(R.id.lxdh_et)
    TextView lxdhEt;
    @Bind(R.id.cxcljcd_img)
    ImageView cxcljcdImg;
    @Bind(R.id.jcd_lay)
    RelativeLayout jcdLay;
    @Bind(R.id.recycleview)
    NoRecycleView recycleview;
    @Bind(R.id.jczfzr_img)
    ImageView jczfzrImg;
    @Bind(R.id.jczfzr_te)
    TextView jczfzrTe;
    @Bind(R.id.jczfzr_lay)
    LinearLayout jczfzrLay;
    @Bind(R.id.fzk_img)
    ImageView fzkImg;
    @Bind(R.id.fzkfzr_te)
    TextView fzkfzrTe;
    @Bind(R.id.fzkfzr_lay)
    LinearLayout fzkfzrLay;
    @Bind(R.id.zfc_img)
    ImageView zfcImg;
    @Bind(R.id.zfc_te)
    TextView zfcTe;
    @Bind(R.id.zfcfgfzr_lay)
    LinearLayout zfcfgfzrLay;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.ty_lay)
    LinearLayout tyLay;
    @Bind(R.id.zkms_et)
    EditText zkmsEt;
    @Bind(R.id.INQuality2)
    RelativeLayout INQuality2;
    @Bind(R.id.bty_lay)
    LinearLayout btyLay;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.relativeLayout)
    RelativeLayout relativeLayout;
    private String isty = "1";
    private int SIGN2R = 22;
    private int SIGN3R = 33;
    private int SIGN4R = 44;
    private List<String> PicDatas = new ArrayList<>();
    private String SIGN2 = "";
    private String SIGN3 = "";
    private String SIGN4 = "";
    private static String APPID = "5bf211f5";
    private String dictationResultStr;
    private List<String> xf = new ArrayList<>();
    private List<String> zong = new ArrayList<>();

    @Override
    public void onRequestError(String msg) {
        ToastUtils.showShortToast(msg);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fra_sign, container, false);
        ButterKnife.bind(this, view);
        rgSex.setOnCheckedChangeListener(this);
        mPresenter.getData(MyAppliCation.spUtils.getString("REQ_NO"));
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.jczfzr_te, R.id.add_te, R.id.fzkfzr_te, R.id.zfc_te, R.id.INQuality, R.id.INQuality2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.INQuality:
                getkdxf(bzEt);
                break;
            case R.id.INQuality2:
                getkdxf(zkmsEt);
                break;
            case R.id.jczfzr_te:
                Intent intent2 = new Intent(getActivity(), SignTextActivity.class);
                startActivityForResult(intent2, SIGN2R);
                break;
            case R.id.fzkfzr_te:
                Intent intent3 = new Intent(getActivity(), SignTextActivity.class);
                startActivityForResult(intent3, SIGN3R);
                break;
            case R.id.zfc_te:
                Intent intent4 = new Intent(getActivity(), SignTextActivity.class);
                startActivityForResult(intent4, SIGN4R);
                break;
            case R.id.add_te:
                if (isty.equals("1")) {
                    if (Utils.isNull(SIGN2)) {
                        ToastUtils.showShortToast("请签字");
                        return;
                    }
                    AddInquestBean addInquestBean = new AddInquestBean();
                    addInquestBean.setReq_no(MyAppliCation.spUtils.getString("REQ_NO"));
                    addInquestBean.setCOMMENT(bzEt.getText().toString());//备注
                    addInquestBean.setSIGN2(SIGN2);//检测站负责人签字
                    addInquestBean.setSIGN3(SIGN3);//法制科负责人签字
                    addInquestBean.setSIGN4(SIGN4);//执法处分管副处长签字
                    String json = new Gson().toJson(addInquestBean);
                    mPresenter.addData("true", json, getActivity());
                } else {
                    AddInquestBean addInquestBean = new AddInquestBean();
                    addInquestBean.setReq_no(MyAppliCation.spUtils.getString("REQ_NO"));
                    addInquestBean.setCOMMENT(zkmsEt.getText().toString());
                    String json = new Gson().toJson(addInquestBean);
                    mPresenter.addData("false", json, getActivity());
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_Male:
                tyLay.setVisibility(View.VISIBLE);
                btyLay.setVisibility(View.GONE);
                isty = "1";
                break;
            case R.id.rb_FeMale:
                tyLay.setVisibility(View.GONE);
                btyLay.setVisibility(View.VISIBLE);
                isty = "0";
                break;
            default:
                break;
        }
    }

    @Override
    public void getDatas(final SignsBean signsBean) {
        if (signsBean != null && signsBean.getData() != null) {
            jcsjEt.setText(signsBean.getData().getCHECK_TIME());
            jcddEt.setText(signsBean.getData().getCHECK_DIST());
            bzEt.setText(signsBean.getData().getCOMMENT());
            bzEt.setText(signsBean.getData().getCOMMENT());
            cphmTe.setText(signsBean.getData().getVEHICLE_NO() + "," + signsBean.getData().getVEHICLE_NO1());
            zhfbTe.setText(signsBean.getData().getAXLES_LOAD());
            hwmcTe.setText(signsBean.getData().getCARGO_INFO());
            hwccC.setText(signsBean.getData().getCARGO_LENGTH());
            hwccK.setText(signsBean.getData().getCARGO_WIDTH());
            hwccG.setText(signsBean.getData().getCARGO_HEIGHT());
            chzzC.setText(signsBean.getData().getTOTAL_LENGTH());
            chzzK.setText(signsBean.getData().getTOTAL_WIDTH());
            chzzG.setText(signsBean.getData().getTOTAL_HEIGHT());
            chzzEt.setText(signsBean.getData().getTOTAL_WEIGHT());
            yslxTe.setText(signsBean.getData().getROADS());
            if (!Utils.isNull(signsBean.getData().getCHECK_IMG())) {
                OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + signsBean.getData().getCHECK_IMG())
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                if (!Utils.isDestroy(getActivity())) {
                                    Glide.with(getActivity())
                                            .asBitmap()
                                            .load(response.body())
                                            .into(cxcljcdImg);
                                }
                            }
                        });
                cxcljcdImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", signsBean.getData().getCHECK_IMG());
                        gotoActivity(BigPicActivity.class, bundle, false);
                    }
                });
            }
            if (!Utils.isNull(signsBean.getData().getDRIVER_SIGN())) {
                OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + signsBean.getData().getDRIVER_SIGN())
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                if (!Utils.isDestroy(getActivity())) {
                                    if (!Utils.isDestroy(getActivity())) {
                                        Glide.with(getActivity())
                                                .asBitmap()
                                                .load(response.body())
                                                .into(chzqzImg);
                                    }
                                }
                            }
                        });
                chzqzImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", signsBean.getData().getDRIVER_SIGN());
                        gotoActivity(BigPicActivity.class, bundle, false);
                    }
                });
            }

            if (signsBean.getData().getSIGN1() != null) {
                String[] strArr2 = signsBean.getData().getSIGN1().split(",");
                if (strArr2 != null && strArr2.length > 0) {
                    for (int i = 0; i < strArr2.length; i++) {
                        PicDatas.add(strArr2[i]);
                    }
                }
            }
            if (signsBean.getData().getCURRENT_SING().equals("SIGN2")) {//监测站负责人
                jczfzrLay.setVisibility(View.VISIBLE);
            } else if (signsBean.getData().getCURRENT_SING().equals("SIGN3")) {//法制科责人
                fzkfzrLay.setVisibility(View.VISIBLE);
            } else if (signsBean.getData().getCURRENT_SING().equals("SIGN4")) {//执法处负责人
                zfcfgfzrLay.setVisibility(View.VISIBLE);
            }
            if (!Utils.isNull(signsBean.getData().getSIGN2())) {
                OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + signsBean.getData().getSIGN2())
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                jczfzrTe.setVisibility(View.GONE);
                                if (!Utils.isDestroy(getActivity())) {
                                    Glide.with(getActivity())
                                            .asBitmap()
                                            .load(response.body())
                                            .into(jczfzrImg);
                                }

                            }
                        });
                jczfzrImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", signsBean.getData().getSIGN2());
                        gotoActivity(BigPicActivity.class, bundle, false);
                    }
                });
            }
            if (!Utils.isNull(signsBean.getData().getSIGN3())) {
                OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + signsBean.getData().getSIGN3())
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                fzkfzrTe.setVisibility(View.GONE);
                                if (!Utils.isDestroy(getActivity())) {
                                    Glide.with(getActivity())
                                            .asBitmap()
                                            .load(response.body())
                                            .into(fzkImg);
                                }

                            }
                        });
                fzkImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", signsBean.getData().getSIGN3());
                        gotoActivity(BigPicActivity.class, bundle, false);
                    }
                });
            }
            if (!Utils.isNull(signsBean.getData().getSIGN4())) {
                OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + signsBean.getData().getSIGN4())
                        .execute(new FileCallback() {
                            @Override
                            public void onSuccess(Response<File> response) {
                                zfcTe.setVisibility(View.GONE);
                                if (!Utils.isDestroy(getActivity())) {
                                    Glide.with(getActivity())
                                            .asBitmap()
                                            .load(response.body())
                                            .into(zfcImg);
                                }
                            }
                        });
                zfcImg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("pic", signsBean.getData().getSIGN4());
                        gotoActivity(BigPicActivity.class, bundle, false);
                    }
                });
            }
            setAdapter();
        }
    }

    @Override
    public void addDatas(AddBean addBean) {
        ToastUtils.showShortToast(addBean.getMessage());
        Intent intent = new Intent();
        getActivity().setResult(2, intent);
        getActivity().finish();
    }

    private void setAdapter() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleview.setLayoutManager(manager);
        LGRecycleViewAdapter<String> adapter = new LGRecycleViewAdapter<String>(PicDatas) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_sign_fag;
            }

            @Override
            public void convert(LGViewHolder holder, String zCDBean, final int position) {
                final ImageView PicView = (ImageView) holder.getView(R.id.img_view);
                if (!Utils.isNull(PicDatas.get(position))) {
                    OkGo.<File>get(Urls.SERVER + "/road/lictran/file/viewImgForApp?KEY=" + PicDatas.get(position))
                            .execute(new FileCallback() {
                                @Override
                                public void onSuccess(Response<File> response) {
                                    if (!Utils.isDestroy(getActivity())) {
                                        Glide.with(getActivity())
                                                .asBitmap()
                                                .load(response.body())
                                                .into(PicView);
                                    }
                                }
                            });
                    PicView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putString("pic", PicDatas.get(position));
                            gotoActivity(BigPicActivity.class, bundle, false);
                        }
                    });
                }

            }
        };
        recycleview.setAdapter(adapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -2) {
            if (requestCode == SIGN2R) {
                jczfzrImg.setVisibility(View.VISIBLE);
                jczfzrTe.setVisibility(View.GONE);
                if (!Utils.isDestroy(getActivity())) {
                    Glide.with(getActivity())
                            .load("data:image/png;base64," + data.getStringExtra("strBlob"))
                            .into(jczfzrImg);
                }
                SIGN2 = data.getStringExtra("strBlob");
            } else if (requestCode == SIGN3R) {
                fzkImg.setVisibility(View.VISIBLE);
                fzkfzrTe.setVisibility(View.GONE);
                if (!Utils.isDestroy(getActivity())) {
                    Glide.with(getActivity())
                            .load("data:image/png;base64," + data.getStringExtra("strBlob"))
                            .into(fzkImg);
                }
                SIGN3 = data.getStringExtra("strBlob");
            } else if (requestCode == SIGN4R) {
                zfcImg.setVisibility(View.VISIBLE);
                zfcTe.setVisibility(View.GONE);
                if (!Utils.isDestroy(getActivity())) {
                    Glide.with(getActivity())
                            .load("data:image/png;base64," + data.getStringExtra("strBlob"))
                            .into(zfcImg);
                }
                SIGN4 = data.getStringExtra("strBlob");
            }
        }
    }

    private void getkdxf(final EditText kdaxfdate) {
        dictationResultStr = "[";
        // 语音配置对象初始化
        SpeechUtility.createUtility(getActivity(), SpeechConstant.APPID + "=" + APPID);
        // 1.创建SpeechRecognizer对象，第2个参数：本地听写时传InitListener
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(getActivity(), null);
        // 交互动画
        final RecognizerDialog iatDialog = new RecognizerDialog(getActivity(), null);
        // 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
        mIat.setParameter(SpeechConstant.DOMAIN, "iat");
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 3.开始听写
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult results, boolean isLast) {

                if (!isLast) {
                    dictationResultStr += results.getResultString() + ",";
                } else {
                    dictationResultStr += results.getResultString() + "]";
                }
                if (isLast) {
                    List<DictationResult> dictationResultList = JSON.parseArray(dictationResultStr, DictationResult.class);
                    String finalResult = "";
                    for (int i = 0; i < dictationResultList.size() - 1; i++) {
                        finalResult += dictationResultList.get(i)
                                .toString();
                    }
                    xf.clear();
                    zong.clear();
                    zong.add(kdaxfdate.getText().toString());
                    zong.add(finalResult);
                    kdaxfdate.setText(listToString2(zong));
                    kdaxfdate.requestFocus();
                    kdaxfdate.setSelection(listToString2(zong).length());
                }
            }

            @Override
            public void onError(SpeechError error) {
                error.getPlainDescription(true);
            }

        });
        iatDialog.show();

    }

    public static String listToString2(List<String> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i));
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }
}
